import java.math.BigDecimal;
import java.math.RoundingMode;

public class AverageCapitalPlusInterest extends Capital {

    public AverageCapitalPlusInterest(BigDecimal loanMoney, BigDecimal yearRate, int totalMonth) {
        this.loanMoney = loanMoney;
        this.yearRate = yearRate;
        this.totalMonth = totalMonth;
    }
    @Override
    public void calculate() {
        //总利息清零
        totalInterest = new BigDecimal("0");
        //月利率
        BigDecimal monthRate = yearRate.divide(new BigDecimal("12"),15,RoundingMode.HALF_UP);
        //a = 1+月利率
        double a = monthRate.add(new BigDecimal("1")).doubleValue();
        //var1 = (1+月利率)^还款月数
        BigDecimal var1 = BigDecimal.valueOf(Math.pow(a, totalMonth));
        //var2 = (1+月利率)^还款月数-1
        BigDecimal var2 = var1.subtract(new BigDecimal("1"));
        for(int i=1;i<=totalMonth;i++) {
            //var3 = (1+月利率)^还款月序号-1
            BigDecimal var3 = BigDecimal.valueOf(Math.pow(a, i-1));
            monthTotalPayment = loanMoney
                    .multiply(monthRate)
                    .multiply(var1)
                    .divide(var2,0, RoundingMode.CEILING);
            monthInterest = loanMoney
                    .multiply(monthRate)
                    .multiply(var1.subtract(var3))
                    .divide(var2,0, RoundingMode.CEILING);
            monthPrinciple = loanMoney
                    .multiply(monthRate)
                    .multiply(var3)
                    .divide(var2,0,  RoundingMode.CEILING);
            //总利息
            totalInterest = totalInterest.add(monthInterest);
            System.out.println("第"+i+"月：月供额:"+monthTotalPayment+"，该月应还利息:"+monthInterest+
                    "，该月应还本金:"+monthPrinciple);
        }
        System.out.println("该还款方式总利息为"+totalInterest);
    }
}
